//
//  VolunteersVC.m
//  MZJ
//
//  Created by XDD on 16/6/4.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "VolunteersVC.h"
#import "VolunteersCell.h"
#import "VolunteerDetailVC.h"
#import "MJRefresh.h"
#import "MyPublic_EditVC.h"
#import "EditDataController.h"

@interface VolunteersVC ()<UITableViewDelegate,UITableViewDataSource> {
    NSInteger page;
}

@property (nonatomic, strong) UITableView *Volunteers_TabelView;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) ModelViewController *modelViewController;
@property (nonatomic, strong) NSMutableArray *allarr;
@property (nonatomic, strong) NSArray *arr2;

@end

@implementation VolunteersVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    self.titleLabel.text = @"志愿者";
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.backButton setTitle:@"" forState:UIControlStateNormal];
    
    UIButton *public_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    public_Btn.frame = CGRectMake(kWidth - 70, 28, 60, 25);
    [public_Btn setTitle:@"我要报名" forState:UIControlStateNormal];
    [public_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    public_Btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [public_Btn addTarget:self action:@selector(public_BtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topBar addSubview:public_Btn];
    
    self.Volunteers_TabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - 55)];
    self.Volunteers_TabelView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    self.Volunteers_TabelView.delegate = self;
    self.Volunteers_TabelView.dataSource = self;
    [self.Volunteers_TabelView registerNib:[UINib nibWithNibName:@"VolunteersCell" bundle:nil] forCellReuseIdentifier:@"volunteersCell"];
    self.Volunteers_TabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.Volunteers_TabelView];

    
    page = 1;
    _allarr = [NSMutableArray array];
    //调网络请求接口
    if (!_modelViewController) {
        _modelViewController = [[ModelViewController alloc]init];
        if (!_model) {
            
            _model = [[NetWorkingSModel alloc] init];
            
            [self requestnetwork];
        }
    }
    
    //下拉刷新
    self.Volunteers_TabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _allarr = nil;
        if (_allarr == nil) {
            //            _allarr = [NSMutableArray array];
            page = 1;
            [self requestnetwork];
        }
        // 结束刷新
        [self.Volunteers_TabelView.mj_header endRefreshing];
        
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.Volunteers_TabelView.mj_header.automaticallyChangeAlpha = YES;
    
    
    // 上拉刷新
    self.Volunteers_TabelView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        page++;
        [self requestnetwork];
        //        // 结束刷新
        [self.Volunteers_TabelView.mj_footer endRefreshing];
    }];
}

-(void)requestnetwork{
    
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user objectForKey:@"user_token"];
    
    if (token.length != 0) {
        [dic setObject:token forKey:@"token"];
        [dic setObject:[NSString stringWithFormat:@"%ld",(long)page] forKey:@"page"];
    }else {
        [dic setObject:[NSString stringWithFormat:@"%ld",(long)page] forKey:@"page"];
    }
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        NSLog(@"志愿者详情 = %@",returnValue);
        weakSelf.arr2 = returnValue[@"result"];
        
        if ( page == 1) {
            weakSelf.allarr = [NSMutableArray array];
        }
        [weakSelf.allarr addObjectsFromArray:weakSelf.arr2];
        
        [weakSelf.Volunteers_TabelView reloadData];
        [weakSelf.Volunteers_TabelView.mj_footer resetNoMoreData];
        
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"没有更多数据");
        NSLog(@"%@",errorCode);
        // 结束刷新
        [weakSelf.Volunteers_TabelView.mj_footer endRefreshingWithNoMoreData];
    }];
    [weakSelf.model homeAppGetaccorder:dic];
    
}

//我要报名
- (void)public_BtnAction {
    if ([[DataModel object].statu_Str intValue] == 0) {
        if ([[DataModel object].userDetail[@"utype"] intValue] == 1) {
            [self waringAction:@"您已经是志愿者啦！"];
        } else {
            __weak typeof (self)weakSelf = self;
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString *token = [user objectForKey:@"user_token"];
            
            if (token.length != 0) {
                [dic setObject:token forKey:@"token"];
            }

            [_model setBlockWithReturnBlock:^(id returnValue) {
                
                NSLog(@"成为志愿者 = %@",returnValue);
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"报名成功!" preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                    [weakSelf requestnetwork];

                }]];
                [weakSelf presentViewController:alertController animated:YES completion:nil];

                
            } WithErrorBlock:^(id errorCode) {

                if ([errorCode[@"statu"] intValue] == 24) {

                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:errorCode[@"result"] preferredStyle:UIAlertControllerStyleAlert];
                    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
                    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        EditDataController *editDataController = [[EditDataController alloc]init];
                        [weakSelf.navigationController pushViewController:editDataController animated:YES];
                        
                    }]];
                    [weakSelf presentViewController:alertController animated:YES completion:nil];

                }

            }];
            [weakSelf.model PayappGetApply_volunteer:dic];

        }
    } else {
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _allarr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

//Header的高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {

    return 3*XJVerticalMultiplier();
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *head = [[UIView alloc]init];
//    if (section == 0) {
//        head.frame = XJFlexibleFrame(CGRectMake(0, 0, 320, 34), NO);
//        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    
//        UIView *searchView = [[UIView alloc]initWithFrame:XJFlexibleFrame(CGRectMake(50, 4, 220, 26), NO)];
//        searchView.backgroundColor = [UIColor whiteColor];
//        searchView.layer.cornerRadius = 13.0*XJVerticalMultiplier();
//        searchView.layer.masksToBounds = YES;
//        searchView.layer.borderWidth = 1.0;
//        searchView.layer.borderColor = [[UIColor grayColor]CGColor];
//        [head addSubview:searchView];
//        
//        UITextField *searchTextfd = [[UITextField alloc]initWithFrame:XJFlexibleFrame(CGRectMake(10, 6, 165, 16), NO)];
//        searchTextfd.placeholder = @"可输入昵称或星级";
//        //        searchTextfd.layer.cornerRadius = 15.0*XJVerticalMultiplier();
//        //        searchTextfd.layer.masksToBounds = YES;
//        searchTextfd.backgroundColor = [UIColor yellowColor];
//        searchTextfd.font = [UIFont systemFontOfSize:11];
//        [searchView addSubview:searchTextfd];
//        
//        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//        searchBtn.frame = XJFlexibleFrame(CGRectMake(180, 2, 38, 22), NO);
//        searchBtn.backgroundColor = [UIColor greenColor];
//        [searchView addSubview:searchBtn];
//        
//        UIImageView *searchImageView = [[UIImageView alloc]initWithFrame:XJFlexibleFrame(CGRectMake(15, 0, 22, 22), YES)];
//        searchImageView.backgroundColor = [UIColor purpleColor];
//        searchImageView.layer.masksToBounds = YES;
//        searchImageView.layer.cornerRadius = 11.0*XJVerticalMultiplier();
//        [searchBtn addSubview:searchImageView];
        
//        return head;
//    }else {
    head.frame = XJFlexibleFrame(CGRectMake(0, 0, 320, 3), NO);
    head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        
        return head;
//    }
    
//    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger section = indexPath.section;
    
    static NSString *identifier = @"volunteersCell";
    VolunteersCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!cell) {
        
        cell = [[VolunteersCell alloc] initWithFrame:CGRectZero];
    }
    cell.nameLabel.text = _allarr[indexPath.section][@"unickname"];
    cell.starNumLabel.text = [NSString stringWithFormat:@"%@ 星",_allarr[indexPath.section][@"ulevel"]];
    cell.dateLabel.text = [_modelViewController TimeStamp:_allarr[indexPath.section][@"acutime"] form_time:@"yyyy-MM-dd"];
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:_allarr[indexPath.section][@"uheadimg"]]
                              placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    VolunteerDetailVC *volunteerDetailVC = [[VolunteerDetailVC alloc]init];
    [DataModel object].Volunteer_ID_Str = [NSString stringWithFormat:@"%@",_allarr[indexPath.section][@"uid"]];
    [self.navigationController pushViewController:volunteerDetailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
